package com.easemob.cases.db;

import android.content.ContentValues;
import android.text.TextUtils;
import android.util.Log;

import com.easemob.cases.db.MessageInviteTable.InviteMessageStatus;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.wechat.android.app.db.DbHelper;
import com.wechat.android.app.rxbus.Message;

import org.xutils.DbManager;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * Created by wangyang on 2017/12/14 0008.
 */
public class MessageDBHelper {

    private static DbManager db ;
    private static MessageDBHelper mInstance = null;
    public static synchronized MessageDBHelper getInstance(){
        if(mInstance == null){
            db  = DbHelper.getInstance().getDb();
            mInstance = new MessageDBHelper();
        }
        return mInstance;
    }

    /**
     * save contact list
     *
     * @param contactList
     */
    synchronized public void saveContactList(List<EaseUser> contactList) {
        List<MessageUserTable> userList = new ArrayList<>();
        for (EaseUser user : contactList) {
            MessageUserTable tmpUser = new MessageUserTable();
            tmpUser.setUserName(user.getUsername());
            if(user.getNick() != null){
                tmpUser.setNick(user.getNick());}
            if(user.getAvatar() != null){
                tmpUser.setAvatar(user.getAvatar());}
            tmpUser.setUserType(user.getUserType());
        }
        try {
            db.save(userList);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * get contact list
     *
     * @return
     */
    synchronized public Map<String, EaseUser> getContactList() {
        List<MessageUserTable> userList = new ArrayList<>();
        Map<String, EaseUser> users = new Hashtable<String, EaseUser>();
        try {
            userList = db.findAll(MessageUserTable.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(userList==null){
            return  users;
        }
        for (MessageUserTable tmpUser : userList) {
            EaseUser user = new EaseUser(tmpUser.getUserName());
            user.setNick(tmpUser.getNick());
            user.setAvatar(tmpUser.getAvatar());
            user.setEmployeeId(tmpUser.getEmployeeId());
            user.setPhone(tmpUser.getPhone());
            user.setUserType(tmpUser.getUserType());
            EaseCommonUtils.setUserInitialLetter(user);
            users.put(tmpUser.getUserName(), user);
        }
        return users;
    }

    /**
     * delete a contact
     * @param username
     */
    synchronized public void deleteContact(String username){
        try {
            db.delete(MessageUserTable.class, WhereBuilder.b(MessageUserTable.COLUMN_NAME_ID, "=", username));
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * save a contact
     * @param user
     */
    synchronized public void saveContact(EaseUser user){
        MessageUserTable tmpUser = new MessageUserTable();
        tmpUser.setUserName(user.getUsername());
        if(user.getNick() != null){
            tmpUser.setNick(user.getNick());}
        if(user.getAvatar() != null){
            tmpUser.setAvatar(user.getAvatar());}
        if(user.getPhone() != null){
            tmpUser.setPhone(user.getPhone());}
        tmpUser.setUserType(user.getUserType());
        try {
            db.saveOrUpdate(tmpUser);
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    public void setDisabledGroups(List<String> groups){
        setList(MessagePrefTable.COLUMN_NAME_DISABLED_GROUPS, groups);
    }

    public List<String>  getDisabledGroups(){
        return getList(MessagePrefTable.COLUMN_NAME_DISABLED_GROUPS);
    }

    public void setDisabledIds(List<String> ids){
        setList(MessagePrefTable.COLUMN_NAME_DISABLED_IDS, ids);
    }

    public List<String> getDisabledIds(){
        return getList(MessagePrefTable.COLUMN_NAME_DISABLED_IDS);
    }

    synchronized private void setList(String column, List<String> strList){
        StringBuilder strBuilder = new StringBuilder();
        MessagePrefTable mPref  = new MessagePrefTable();

        for(String hxid:strList){
            strBuilder.append(hxid).append("$");
        }

        try {
            mPref = db.findFirst(MessagePrefTable.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(MessagePrefTable.COLUMN_NAME_DISABLED_GROUPS.equals(column)){
            mPref.setDisabledGroups(strBuilder.toString());
        }else {
            mPref.setDisabledIDs(strBuilder.toString());
        }
        try {
            db.saveOrUpdate(mPref);
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    synchronized private List<String> getList(String column){
        MessagePrefTable mPref  = new MessagePrefTable();
        try {
            mPref = db.findFirst(MessagePrefTable.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        if(mPref==null){
            return null;
        }
        String strVal;
        if(MessagePrefTable.COLUMN_NAME_DISABLED_GROUPS.equals(column)){
            strVal =  mPref.getDisabledGroups();
        }else {
            strVal = mPref.getDisabledIDs();
        }

        if (TextUtils.isEmpty(strVal)) {
            return null;
        }
        String[] array = strVal.split("$");

        if(array != null && array.length > 0){
            List<String> list = new ArrayList<String>();
            for(String str:array){
                list.add(str);
            }

            return list;
        }

        return null;
    }

    /**
     * save a message
     * @param message
     * @return  return cursor of the message
     */
    public synchronized Integer saveMessage(MessageInviteTable message){
        int id = -1;
        try {
            db.save(message);
            MessageInviteTable tmpMessage = db.findFirst(MessageInviteTable.class);
            if(tmpMessage!=null){
                id = tmpMessage.getId();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return id;
    }

    /**
     * update message
     * @param msgId
     * @param values
     */
    synchronized public void updateMessage(int msgId,ContentValues values){
        // TODO updateMessage


        /*SQLiteDatabase db = dbHelper.getWritableDatabase();
        if(db.isOpen()){
            db.update(MessageInviteTable.TABLE_NAME, values, MessageInviteTable.COLUMN_NAME_ID + " = ?", new String[]{String.valueOf(msgId)});
        }*/
    }

    /**
     * get messges
     * @return
     */
    synchronized public List<MessageInviteTable> getMessagesList(){
        List<MessageInviteTable> msgs = new ArrayList<>();
        try {
            msgs = db.selector(MessageInviteTable.class).orderBy(MessageInviteTable.COLUMN_NAME_ID,true).findAll();
        } catch (DbException e) {
            e.printStackTrace();
            Log.e("yang","DbException=="+e.toString());
        }
        if(msgs!=null && msgs.size()>0){
            for (int i = 0 ; i < msgs.size() ; i++ ){
                switch (msgs.get(i).getStatus()){
                    case 0:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.BEINVITEED);
                        break;
                    case 1:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.BEREFUSED);
                        break;
                    case 2:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.BEAGREED);
                        break;

                    case 3:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.BEAPPLYED);
                        break;
                    case 4:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.AGREED);
                        break;
                    case 5:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.REFUSED);
                        break;

                    case 6:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.GROUPINVITATION);
                        break;
                    case 7:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.GROUPINVITATION_ACCEPTED);
                        break;
                    case 8:
                        msgs.get(i).setStatusFlag(InviteMessageStatus.GROUPINVITATION_DECLINED);
                        break;
                }

            }
        }

        return msgs;
    }

    /**
     * delete invitation message
     * @param from
     */
    synchronized public void deleteMessage(String from){
        if(db ==null){
            throw new RuntimeException("Please init Message DB!");
        }
        try {
            db.delete(MessageInviteTable.class, WhereBuilder.b(MessageInviteTable.COLUMN_NAME_FROM,"=",from));
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    synchronized int getUnreadNotifyCount(){
        int count = 0;
        try {
            MessageInviteTable tmpMessage = db.findFirst(MessageInviteTable.class);
            if(tmpMessage!=null){
                count = tmpMessage.getUnReadMsgCount();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return count;
    }

    public synchronized void setUnreadNotifyCount(int count){
        try {
            MessageInviteTable tmpMessage = db.findFirst(MessageInviteTable.class);
            if(tmpMessage!=null){
                tmpMessage.setUnReadMsgCount(count);
                db.update(tmpMessage);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


}
